import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter01/pages/sqfLite/sqflite_providers/note_table_provider.dart';
import 'package:flutter01/pages/sqfLite/sqflite_providers/target_table_provider.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';
import 'package:get/get.dart';

import 'controller.dart';
import 'form.dart';

class SqfLite extends StatefulWidget {
  SqfLite({Key? key}) : super(key: key) {
    final NoteTableProvider noteTableProvider = NoteTableProvider();
    final TargetTableProvider targetTableProvider = TargetTableProvider();
    noteTableProvider.createTable();
    targetTableProvider.createTable();
  }

  @override
  _SqfLiteState createState() => _SqfLiteState();
}

class _SqfLiteState extends State<SqfLite> {
  final data = [].obs;
  final loading = false.obs;

  final controller = Get.find<SqfLiteController>();

  final formKey = GlobalKey();
  final sqfLiteFormStateKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    loading.value = true;
    Dio().get("http://jsonplaceholder.typicode.com/posts").then((res) {
      // setState(() {
      //   data = (res.data as List).sublist(0, 6);
      // });
      data.value = (res.data as List).sublist(0, 6);
    }).catchError((error) {
      print("http get has error:$error");
    }).whenComplete(() {
      loading.value = false;
    });
  }

  Widget _getPanel() {
    return SqfLiteForm(key: sqfLiteFormStateKey, formKey: formKey);
  }

  Widget _getBody() {
    return Container(
      child: Obx(() => AnimatedSwitcher(
            transitionBuilder: (Widget child, Animation<double> animation) {
              //执行缩放动画
              return ScaleTransition(
                child: child,
                // scale: Tween(begin: 0.8, end: 1.0).animate(animation),
                // scale:Tween(begin:0.8,end:1.0).chain(CurveTween(curve: Curves.bounceIn)).animate(animation),
                scale: Tween(begin: 0.8, end: 1.0).animate(
                    CurvedAnimation(curve: Curves.bounceIn, parent: animation)),
              );
            },
            duration: 300.milliseconds,
            child: loading.value
                ? Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return SwipeActionCell(
                        key: ObjectKey(data[index]["id"]),
                        trailingActions: <SwipeAction>[
                          SwipeAction(
                              title: "delete",
                              icon: Icon(
                                CupertinoIcons.trash,
                                color: Colors.white,
                              ),
                              onTap: (CompletionHandler handler) async {
                                /// await handler(true) : will delete this row
                                ///And after delete animation,setState will called to
                                /// sync your data source with your UI
                                Get.defaultDialog(
                                  title: '确定要删除吗？',
                                  textConfirm: '确定',
                                  textCancel: '取消',
                                  onConfirm: () async {
                                    Get.back();
                                    await handler(true);
                                    data.removeAt(index);
                                  },
                                  onCancel: () {
                                    handler(false);
                                  },
                                );
                                // await handler(true);
                              },
                              color: Colors.red),
                        ],
                        child: ListTile(
                          leading: Icon(CupertinoIcons.add_circled),
                          title: Text(data[index]["title"]),
                          subtitle: Text(data[index]["body"]),
                        ),
                      );
                    },
                    itemCount: data.length),
          )),
      //     FutureBuilder(
      //   future: Dio().get("http://jsonplaceholder.typicode.com/posts"),
      //   builder: (context, snapshot) {
      //     if (snapshot.hasData) {
      //       final data = ((snapshot.data as Response<dynamic>).data as List)
      //           .sublist(0, 5);
      //
      //       return ListView.builder(
      //         itemBuilder: (BuildContext context, int index) {
      //           return ListTile(
      //             leading: Text(data[index]["id"].toString()),
      //             title: Text(data[index]["title"]),
      //             subtitle: Text(data[index]["body"]),
      //           );
      //         },
      //         itemCount: data.length,
      //       );
      //     } else if (snapshot.hasError) {
      //       return Text('Error: ${snapshot.error}');
      //     } else {
      //       return Center(
      //         child: CircularProgressIndicator(),
      //       );
      //     }
      //   },
      // ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('sqfLite'),
      ),
      body: SlidingUpPanel(
        // renderPanelSheet: false,
        parallaxEnabled: true,
        controller: controller.slidingUpPanelController,
        minHeight: MediaQuery.of(context).padding.bottom + 30,
        maxHeight: Get.height - 150,
        margin: EdgeInsets.only(
          left: 10,
          right: 10,
          // bottom:context.mediaQueryPadding.bottom,
        ),
        padding: EdgeInsets.symmetric(horizontal: 20),
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24), topRight: Radius.circular(24)),
        collapsed: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 160,
              height: 6,
              margin: EdgeInsets.only(top: 12),
              decoration: BoxDecoration(
                color: Colors.orange,
                borderRadius: BorderRadius.circular(6),
              ),
            )
          ],
        ),
        panel: _getPanel(),
        body: _getBody(),
        onPanelClosed: () {
          final formState = (formKey.currentState as FormState);
          final sqfLiteFormState =
              (sqfLiteFormStateKey.currentState as SqfLiteFormState);
          sqfLiteFormState.setState(() {
            sqfLiteFormState.hasSubmited = false;
            formState.reset();
          });
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          if (controller.slidingUpPanelController.isAttached) {
            if (controller.slidingUpPanelController.isPanelOpen) {
              await controller.slidingUpPanelController.close();
              // await controller.slidingUpPanelController.hide();

            } else {
              // await controller.slidingUpPanelController.show();
              await controller.slidingUpPanelController.open();
            }
          }
        },
      ),
    );
  }
}
